import { baseURL } from "@/config/index";
import { getPublicKey as getPublicKeyApi } from "@/api/publicKey";
import { isNull } from "@/utils/validate";
import { ajax } from "@/utils/request";
import { getCookies, setCookiesByExpiresTime } from "@/utils/cookies";

// Cookie Key
const COOKIE_KEY = "public_key";

interface PublicKeyResponse {
  code: number;
  msg: string;
  data: string;
}

/**
 * 获取公钥
 * @returns [公钥]
 */
export const getPublicKey = () => {
  let publicKey = getCookies(COOKIE_KEY);
  // 如果公钥为空 则去接口查询
  if (isNull(publicKey)) {
    const params = getPublicKeyApi();
    let ret: PublicKeyResponse = { code: 0, msg: '', data: '' };
    ajax({
      url: baseURL + params.url,
      method: params.method,
      async: false,
      success: function (res) {
        ret = JSON.parse(res);
      },
    });
    if (ret && ret.data) {
      publicKey = ret.data;
      // 存储 公钥到 Cookies 默认存储时长为5分钟
      setCookiesByExpiresTime(COOKIE_KEY, publicKey, 300);
    }
  }

  return publicKey;
}; 